package com.cjr.mq.cases.controller;

import com.cjr.mq.cases.config.RabbitConfig;
import com.cjr.mq.cases.entity.OrderInfo;
import com.cjr.mq.cases.entity.OrderStatusEnum;
import com.cjr.mq.cases.service.OrderService;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.GetResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.ChannelCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
public class PayController {
    private static final Logger logger = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderService orderService;

    // 创建订单接口
    @RequestMapping("/order/create")
    public String order() {
        String orderId = UUID.randomUUID().toString();
        orderService.createOrder(orderId);
        // 发送延迟等待消息
        rabbitTemplate.convertAndSend(RabbitConfig.PAY_EXCHANGE, RabbitConfig.PAY_ROUTING_KEY, orderId);
        return "该订单创建成功，待支付，订单号为：" + orderId;
    }

    // 支付接口
    @RequestMapping("/order/pay/{orderId}")
    public String pay(@PathVariable String orderId) {
        final OrderInfo orderInfo = orderService.findOrderByOrderId(orderId);
        if (orderInfo.getOrderStatus().equals(OrderStatusEnum.HAS_CANCEL.getFlag())) {
            logger.info("该订单【{}】已经取消", orderId);
            final List orderList = list();
            return "该订单已经取消，历史订单表记录为：\n" + Arrays.toString(orderList.toArray());
        }
        String message = rabbitTemplate.execute(new ChannelCallback<String>() {
            @Override
            public String doInRabbit(Channel channel) throws Exception {
                // 主动从业务队列中拉取消息
                final GetResponse getResponse = channel.basicGet(RabbitConfig.PAY_QUEUE, false);
                if (getResponse == null) {
                    logger.info("该消息已经消费");
                    return "你已消费完所有的消息";
                }
                String message = new String(getResponse.getBody(), StandardCharsets.UTF_8);
                channel.basicAck(getResponse.getEnvelope().getDeliveryTag(), false);
                logger.info("该消息【{}】已确认", message);
                return message;
            }
        });
        if (!message.equals(orderId)) {
            return message;
        }
        String flag = "pay";
        orderService.updateOrderStatus(orderId, flag);
        return "该订单成功支付，订单号为：" + message;
    }

    // 订单列表
    @RequestMapping("/order/list")
    public List list() {
        return orderService.findAll();
    }
}
